package com.qf.service.impl;/*
 *保护你的大熊
 *2021/11/26
 *17:13
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsAdminMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminAdminService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class AdminAdminServiceImpl implements AdminAdminService {

    @Autowired
    DtsAdminMapper adminMapper;

    @Override
    public IPage<DtsAdmin> queryPage(Integer page, Integer limit, String username, String sort, String order) {
        //配置分页参数
        IPage<DtsAdmin> iPage = new Page();

        //配置除分页以外的条件
        QueryWrapper<DtsAdmin> wrapper = new QueryWrapper<>();

        if( ! StringUtils.isEmpty(username)){
            wrapper.like("username", username);
        }

        if(order.equalsIgnoreCase("asc")){
            wrapper.orderByAsc(sort);
        }else{
            wrapper.orderByDesc(sort);
        }


        iPage = adminMapper.selectPage(iPage,wrapper);

        return iPage;
    }

    @Override
    public boolean findByUsername(String username) {

        LambdaQueryWrapper<DtsAdmin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsAdmin::getUsername,username);

        DtsAdmin admin = adminMapper.selectOne(wrapper);
        if(admin == null){
            return true;
        }
        return false;
    }

    @Override
    public DtsAdmin insert(DtsAdmin admin) {

        admin.setAddTime(new Date());
        admin.setUpdateTime(new Date());
        admin.setDeleted(false);

        //对明文密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(admin.getPassword());
        admin.setPassword(encode);

        adminMapper.insert(admin);
        return admin;
    }

    @Override
    public DtsAdmin update(DtsAdmin admin) {


        DtsAdmin adminDb = adminMapper.selectById(admin.getId());
        //判断  两个密文是否一致
        if( ! admin.getPassword().equals(adminDb.getPassword())){
            //对明文密码加密
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encode = passwordEncoder.encode(admin.getPassword());
            admin.setPassword(encode);
        }
        admin.setUpdateTime(new Date());

        adminMapper.updateById(admin);
        return admin;
    }

    @Override
    public int deleteById(Integer id) {
        int cnt = adminMapper.deleteById(id);
        return cnt;
    }
}
